package coop.bancocredicoop.proyectos.gd.query.document;

import java.util.List;
import java.util.Map;

import org.hibernate.classic.Session;
import org.hibernate.Query;
import org.hibernate.Transaction;

import coop.bancocredicoop.proyectos.gd.domain.Box;
import coop.bancocredicoop.proyectos.gd.domain.Customer;
import coop.bancocredicoop.proyectos.gd.domain.Document;
import coop.bancocredicoop.proyectos.gd.hibernate.HibernateUtil;
import coop.bancocredicoop.proyectos.gd.query.box.FindBoxByCajaId;
import coop.bancocredicoop.proyectos.gd.query.customer.FindCustomerByIdPersona;

public class FindDocumentByMap {

	public List<Document> run(Map<String, String> map) throws Exception {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		List<Document> listResult = null;

		try {
			tx = session.beginTransaction();

			listResult = run(map, session);

			tx.commit();
		}
		catch (Exception e) {
			if (tx!=null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

		return listResult;

	}

	public List<Document> run(Map<String, String> map, Session session) throws Exception {

		StringBuilder strbld = new StringBuilder(" from Document where deleteDate is null");

		Customer customer = null;
		if (map.get("customerId") != null && !map.get("customerId").trim().equals("")) {
			customer = new FindCustomerByIdPersona().run(
					Long.valueOf(map.get("customerId")), session);

			if (customer == null)
				return null;
		}

		Box box = null;
		if (map.get("cajaId") != null && !map.get("cajaId").trim().equals("")) {
			box = new FindBoxByCajaId().run(
					map.get("cajaId"), session);

			if (box == null)
				return null;
		}

		if (customer != null)
			strbld.append(" and customer = :customer ");

		if (box != null)
			strbld.append(" and box = :box ");

		Query query = session.createQuery(strbld.toString());

		if (customer != null)
			query.setEntity("customer", customer);

		if (box != null)
			query.setEntity("box", box);

		return query.list();

	}

}
